package com.hmall.item.web;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.apache.http.client.AuthenticationStrategy;
import org.springframework.amqp.rabbit.connection.RabbitAccessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public PageDTO<Item> page(@RequestParam Integer page,@RequestParam Integer size){
         Page<Item> page1 = itemService.page(new Page<>(page, size));
        return new PageDTO<>(page1.getTotal(),page1.getRecords());
    }

    @GetMapping("/{id}")
    public Item select(@PathVariable Long id){
       return itemService.getById(id);
    }

    @PostMapping
    public void insert(@RequestBody Item item){
        itemService.save(item);
    }

    @PutMapping("/status/{id}/{status}")
    @Transactional
    public void up(@PathVariable Long id,@PathVariable Integer status){
        final Item item = new Item();
        item.setStatus(status);
        item.setId(id);
        String routingKey=status==1?"item.up":"item.down";
        rabbitTemplate.convertAndSend("item.topic",routingKey,id);
            itemService.saveOrUpdate(item);
    }

    @PutMapping
    public void upload(@RequestBody Item item){
        if (item.getStatus()==2){
            itemService.saveOrUpdate(item);
        }
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){

         itemService.removeById(id);
    }
}
